package com.example.spider.web;

import io.prometheus.client.Collector;
import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.exporter.common.TextFormat;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Enumeration;
import java.util.Optional;

/**
 * http://localhost:8080/status
 * http://localhost:8080/status/thread_pool,Holder
 * http://localhost:8080/status/SPD_spider_metrics_
 */
@RequestMapping("status")
@Controller
public class StatusController {

    private final CollectorRegistry collectorRegistry;
    private volatile int nextMetricsScrapeSize = 16;

    public StatusController(CollectorRegistry collectorRegistry) {
        this.collectorRegistry = collectorRegistry;
    }

    @ResponseBody
    @RequestMapping(value = "{filterName}", produces = "text/plain; version=0.0.4; charset=utf-8")
    public String status(@PathVariable("filterName") String filterName, HttpServletResponse response) throws IOException {
        response.setContentType("text/plain; version=0.0.4; charset=utf-8");
        CharSequence[] includedNames = Optional.ofNullable(filterName).map(s -> s.split(",")).orElse(null);
        Writer writer = new StringWriter(this.nextMetricsScrapeSize);
        Enumeration<Collector.MetricFamilySamples> samples = includedNames != null ? this.collectorRegistry.filteredMetricFamilySamples(l -> StringUtils.containsAny(l, includedNames)) : this.collectorRegistry.metricFamilySamples();
        TextFormat.write004(writer, samples);
        String scrapePage = writer.toString();
        this.nextMetricsScrapeSize = scrapePage.length() + 1024;
        return scrapePage;
    }

    @ResponseBody
    @RequestMapping(value = "", produces = "text/plain; version=0.0.4; charset=utf-8")
    public String statusAll(HttpServletResponse response) throws IOException {

        return status(null, response);
    }
}
